﻿	 
using System;
using System.Collections.Generic;
using System.Linq;
using RBAC.DAL.Entities;
using NHibernate;
using NHibernate.Criterion;
using RBAC.DAL.Models;


namespace RBAC.DAL.Dal
{
    public class PermissionDAL
    {
        private readonly ISession _session;
        public PermissionDAL(ISession session)
        {
             this._session = session;
        }

        public List<Permission> GetAll(PermissionSearch searchCriteria)
        {
            var criteria = _session.CreateCriteria(typeof(Permission));

            if (searchCriteria != null)
            {
                #region Search
				//Pk
																	if (!string.IsNullOrEmpty(searchCriteria.PermissionName)) 
							{
								if (searchCriteria.EqPk.GetValueOrDefault())
									{
										criteria.Add(Restrictions.Eq("PermissionName", searchCriteria.PermissionName)); 
									}
								else
									{
										criteria.Add(Restrictions.Like("PermissionName", searchCriteria.PermissionName, MatchMode.Anywhere));
									}
							}
									  			  //lookup to parent
			  			  if (null != searchCriteria.Role)
                {
                    criteria.Add(Restrictions.Eq("Role", searchCriteria.Role));
                }
			  		  
			 #endregion
					
					#region Sort
					if (searchCriteria.IsSort)
						criteria.AddOrder(searchCriteria.Order);
                    #endregion            
            }			
            return criteria.List<Permission>().ToList();
        }


        public void Add(Permission permission)
        {
			          _session.Save( permission);
        }

        public void Update(Permission permission)
        {
			
				 // chlidren

            var obj = _session.Get<Permission>(permission.Id);
            if (obj == null)
                throw new Exception("Update Not Success");
			            
            _session.Merge(permission);			
           
        }

        public void Delete(List<string> idList)
        {
            int row = _session.CreateQuery("DELETE RBAC.DAL.Entities.Permission where Id in (:IdList)").SetParameterList("IdList", idList).ExecuteUpdate();
            if (row != idList.Count)
                throw new Exception("Delete Not Success");
        }
    }
}

